package com.usian.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.usian.UserFeign;
import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Value("${config.info}")
    private String configInfo;

    @Autowired
    private UserFeign userFeign;


    @RequestMapping("/findById/{id}")
    public User findById(@PathVariable Integer id){

        //1:通过服务获取实例  serviceId = 要调用的微服务的服务名（yml spring.application.name=）
        ServiceInstance instance = loadBalancerClient.choose("provider");

        //2:拼接请求路径  http://localhost:9091/findById/8
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/findById/"+id;
        User user = restTemplate.getForObject(url, User.class);

        System.out.println("=======:"+configInfo);

        return user;
    }


    /**
     * 使用feign 做远程调用
     *
     * @param id
     * @return
     */
    @RequestMapping("/findByIds/{id}")
    @SentinelResource(value = "findByIds/{id}",
                     blockHandler = "blockTest",
                     fallback = "fallTest")
    public User findByIds(@PathVariable Integer id){
        //int y = 100/0;
        User user = userFeign.findById(id);
        return user;
    }
    public User blockTest(@PathVariable Integer id, BlockException e){
        return new User(1,"block托底",0);
    }

    public User fallTest(@PathVariable Integer id,Throwable e){
        return new User(1,"fall托底",0);
    }

    @RequestMapping("/findByName")
    public User findByName(Integer id,String name ){
       return  userFeign.findByName(id,name);
    }

    @PostMapping("/findByUser")
    public User findByUser(@RequestBody User user){
        return userFeign.findByUser(user);
    }

}
